
package com.platform.modules.mall.bank;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.platform.common.annotation.SysLog;
import com.platform.common.exception.BusinessException;
import com.platform.common.utils.EasyPoiUtils;
import com.platform.common.utils.RestResponse;
import com.platform.common.utils.StringUtils;
import com.platform.modules.mall.dao.MallBranchDao;
import com.platform.modules.mall.entity.MallBranchEntity;
import com.platform.modules.mall.service.MallBranchService;
import com.platform.modules.sys.controller.AbstractController;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 网点Controller
 *
 * @author
 * @date 2021-04-20 09:59:04
 */
@Slf4j
@RestController
@RequestMapping("mall/branch")
public class MallBranchController extends AbstractController {
    @Autowired
    private MallBranchService mallBranchService;

    /**
     * 上传文件 （目前逻辑 只支持 共存（1级和2级网点）|（2级3级网点）的情况）
     *
     * @param file file
     * @return RestResponse
     */
    @SysLog("网点导入")
    @RequestMapping("/upload")
    @RequiresPermissions("mall:cardsn:save")
    public Object upload(@RequestParam(value = "file", required = false) MultipartFile file) throws Exception {
        if (null == file || file.isEmpty()) {
            throw new BusinessException("文件不能为空");
        }

        //上传文件
        Date date = new Date();
        List<MallBranchEntity> branchEntityList = EasyPoiUtils.importExcelToMap(file, (row) -> {
            if (StringUtils.isNotBlank(row[1]) && StringUtils.isNotBlank(row[0])) {
                // 为空判断
                if (StringUtils.isBlank(row[1]) || StringUtils.isBlank(row[0]) || StringUtils.isBlank(row[2])) {
                    throw new BusinessException("关键数据为空！");
                }
                if (mallBranchService.branchExists(row[1])) {
                    log.error("网点导入数据重复：" + JSONObject.toJSONString(row));
                    return null;
                }
                MallBranchEntity branchEntity = new MallBranchEntity();
                // 总行判断
                if (!row[1].trim().contains(row[0].trim())) {
                    // 不为总行
                    if (row[0].trim().getBytes(StandardCharsets.UTF_8).length > 31) {
                        throw new BusinessException("一级支行名称过长【大于31字节】！");
                    }
                    branchEntity.setParentId(row[0].trim());
                    branchEntity.setHierarchy(2);
                } else {
                    branchEntity.setHierarchy(1);
                }
                branchEntity.setName(row[1].trim());
                branchEntity.setDetails(row[2].trim());
                if (row.length > 3 && StringUtils.isNotBlank(row[3])) {
                    branchEntity.setLatitude(row[3].trim().split(",")[0]);
                    branchEntity.setLongitude(row[3].trim().split(",")[1]);
                }
                branchEntity.setCreateTime(date);
                return branchEntity;
            }
            return null;
        });
        if (branchEntityList.size() > 0) {
            mallBranchService.saveBatch(branchEntityList);
        } else {
            return RestResponse.error("无可录入数据！");
        }
        /*
        直接运行以下逻辑就行
        UPDATE mall_branch a left join (select `name`,id from mall_branch where parent_id is NULL) b on b.`name` like CONCAT(a.parent_id,'%') set a.PARENT_ID = b.id where b.`name` is not NULL
         */
        // 批量更新 1、2级支行引用关系
        mallBranchService.updateBanchRelation();

        //批量添加到腾讯云地图
//        int i = 0;
//        StringBuffer errorMessages = new StringBuffer();
//        Map<String, String> params = null;
//        for (MallBranchEntity item : branchEntityList) {
//            i++;
//            params = new HashMap<>();
//            params.put("id", item.getId());
//            params.put("latitude", item.getLatitude());
//            params.put("longitude", item.getLongitude());
//            params.put("name", item.getName());
//            params.put("address", item.getDetails());
//            //添加到腾讯云地图
//            try {
//                String errorMessage = tencentMapUtil.createOrUpdateCloud(true, params, tencentMapUtil.tencentMapTableIdBranch);
//                if (errorMessage != null) {
//                    throw new BusinessException(errorMessage);
//                }
//            } catch (Exception e) {
//                mallBranchService.delete(item.getId());
//                errorMessages.append(String.format("第 %s 行数据导入失败！ 原因：【%s】", i, e.getMessage())).append("\n");
//            }
//        }
//        if (errorMessages.length() > 0) {
//            log.error("\n" + errorMessages.toString());
//            return RestResponse.error(errorMessages.toString());
//        }
        return RestResponse.success();
    }

    /**
     * 查看所有列表
     *
     * @param params 查询参数
     * @return RestResponse
     */
    @RequestMapping("/queryAll")
    @RequiresPermissions("mall:branch:list")
    public RestResponse queryAll(@RequestParam Map<String, Object> params) {
        List<MallBranchEntity> list = mallBranchService.queryAll(params);
        return RestResponse.success().put("list", list);
    }

    /**
     * 分页查询网点
     *
     * @param params 查询参数
     * @return RestResponse
     */
    @GetMapping("/list")
    @RequiresPermissions("mall:branch:list")
    public RestResponse list(@RequestParam Map<String, Object> params) {
        Page page = mallBranchService.queryPage(params);

        return RestResponse.success().put("page", page);
    }

    /**
     * 根据主键查询详情
     *
     * @param id 主键
     * @return RestResponse
     */
    @RequestMapping("/info/{id}")
    @RequiresPermissions("mall:branch:info")
    public RestResponse info(@PathVariable("id") String id) {
        MallBranchEntity mallBranch = ((MallBranchDao) mallBranchService.getBaseMapper()).getBranchById(id);

        return RestResponse.success().put("branch", mallBranch);
    }

    /**
     * 新增网点
     *
     * @param mallBranch mallBranch
     * @return RestResponse
     */
    @SysLog("新增网点")
    @RequestMapping("/save")
    @RequiresPermissions("mall:branch:save")
    public RestResponse save(@RequestBody MallBranchEntity mallBranch) throws Exception {
        mallBranch.setCreateTime(new Date());
        mallBranch.setCreateUserId(getUserId());
        try {
            mallBranchService.add(mallBranch);
        } catch (Exception e) {
            return RestResponse.error(e.getMessage());
        }
        return RestResponse.success();
    }

    /**
     * 修改网点
     *
     * @param mallBranch mallBranch
     * @return RestResponse
     */
    @SysLog("修改网点")
    @RequestMapping("/update")
    @RequiresPermissions("mall:branch:update")
    public RestResponse update(@RequestBody MallBranchEntity mallBranch) {
        Map<String, String> params = new HashMap<>();
        params.put("id", mallBranch.getId());
        params.put("latitude", mallBranch.getLatitude());
        params.put("longitude", mallBranch.getLongitude());
        params.put("name", mallBranch.getName());
        params.put("address", mallBranch.getDetails());
//        try {
//            //腾讯云地图数据更新
//            String errorMessage = tencentMapUtil.createOrUpdateCloud(false, params, tencentMapUtil.tencentMapTableIdBranch);
//            if (errorMessage != null) {
//                return RestResponse.error("地点云修改失败 原因：【" + errorMessage + "】");
//            }
//        } catch (Exception e) {
//            return RestResponse.error("地点云修改失败 原因：【" + e.getMessage() + "】");
//        }

        mallBranch.setUpdateTime(new Date());
        mallBranchService.update(mallBranch);

        return RestResponse.success();
    }

    /**
     * 根据主键删除网点
     *
     * @param ids ids
     * @return RestResponse
     */
    @SysLog("删除网点")
    @RequestMapping("/delete")
    @RequiresPermissions("mall:branch:delete")
    public RestResponse delete(@RequestBody String[] ids) {
//        String errorMessage = tencentMapUtil.deleteCloud(tencentMapUtil.tencentMapTableIdBranch, ids);
//        if (errorMessage != null) {
//            return RestResponse.error("地点云删除失败 原因：【" + errorMessage + "】");
//        }
        mallBranchService.deleteBatch(ids);
        return RestResponse.success();
    }
}
